package com.zhangpp.controller;

import com.zhangpp.entity.Admin;
import com.zhangpp.service.AdminService;
import com.zhangpp.util.ImageCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("admin")
public class AdminController {

    @Resource
    AdminService adminService;

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    @PostMapping("getImageCodes")
    public String getImageCodes(HttpServletRequest request){

        String code = ImageCodeUtil.getSecurityCode();
        log.info("验证码为：{}",code);
        request.getServletContext().setAttribute("code",code);
        String imgBase64 = null;
        try {
            imgBase64 = ImageCodeUtil.careateImgBase64(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgBase64;
    }

    @PostMapping("login")
    public HashMap<String, Object> login(@RequestBody Admin admin, String enCode){

        log.info("用户输入的admin:{}",admin);
        log.info("用户输入的验证码:{}",enCode);
        HashMap<String, Object> login = adminService.login(admin, enCode);
        return login;
    }

    @PostMapping("logout")
    public void logout(HttpServletRequest request){

        log.info("退出登录");
        //删除用户登录标记
        request.getServletContext().removeAttribute("admin");

    }
}
